<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>居中元素</title>
  <style>
    .btn-x {
      margin-bottom: 10px;
    }
    #canvasBox {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <div class="btn-x">
    <button onclick="viewportCenterObjectH()">水平居中</button>
    <button onclick="viewportCenterObjectV()">垂直居中</button>
    <button onclick="viewportCenterObject()">垂直水平居中</button>
    <button onclick="fxCenterObjectH()">动画水平居中</button>
    <button onclick="fxCenterObjectV()">动画水垂直中</button>
  </div>
  <canvas id="canvasBox" width="600" height="600"></canvas>
  
<script src="../../script/fabric.js"></script>
<script>
  let canvas = null
  let rect = null

  window.onload = function() {
    // 使用 元素id 创建画布，此时可以在画布上框选
    canvas = new fabric.Canvas('canvasBox', {
      width: 400,
      height: 400
    })

    rect = new fabric.Rect({
      name: 'rect',
      top: 60, // 距离容器顶部 60px
      left: 60, // 距离容器左侧 200px
      fill: 'orange', // 填充a 橙色
      width: 60, // 宽度 60px
      height: 60, // 高度 60px
      originX: 'center',
      originY: 'center'
    })

    // 将矩形添加到画布中
    canvas.add(rect)
  }

  // 水平居中
  function viewportCenterObjectH() {
    canvas.viewportCenterObjectH(rect)
    // rect.viewportCenterH()
  }

  // 垂直居中
  function viewportCenterObjectV() {
    canvas.viewportCenterObjectV(rect)
    // rect.viewportCenterV()
  }

  // 垂直水平居中
  function viewportCenterObject() {
    canvas.viewportCenterObject(rect)
    // rect.viewportCenter()
  }

  // 动画水平居中
  function fxCenterObjectH() {
    canvas.fxCenterObjectH(rect)
  }

  // 动画水垂直中
  function fxCenterObjectV() {
    canvas.fxCenterObjectV(rect)
  }

</script>
</body>
</html>